package com.shuda.business.user.service;

import com.shuda.business.user.service.IUserManager;
import com.shuda.common.result.Result;
import com.shuda.common.result.ResultCode;
import com.shuda.db.user.entity.User;
import com.shuda.db.user.service.UserDbService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class UserManager implements IUserManager {
    
    @Autowired
    private UserDbService userDbService;
    
    @Override
    public Result<User> getUserById(Long id) {
        User user = userDbService.getById(id);
        if (user == null) {
            return Result.error("用户不存在");
        }
        return Result.success(user);
    }
    
    @Override
    public Result<User> getUserByUsername(String username) {
        User user = userDbService.getByUsername(username);
        if (user == null) {
            return Result.error("用户不存在");
        }
        return Result.success(user);
    }
    
    @Override
    @Transactional
    public Result<User> createUser(User user) {
        if (userDbService.existsByUsername(user.getUsername())) {
            return Result.error("用户名已存在");
        }
        userDbService.insert(user);
        return Result.success(user);
    }
    
    @Override
    @Transactional
    public Result<User> updateUser(User user) {
        User existingUser = userDbService.getById(user.getId());
        if (existingUser == null) {
            return Result.error("用户不存在");
        }
        userDbService.update(user);
        return Result.success(user);
    }
    
    @Override
    @Transactional
    public Result<Void> deleteUser(Long id) {
        User user = userDbService.getById(id);
        if (user == null) {
            return Result.error("用户不存在");
        }
        userDbService.delete(id);
        return Result.success();
    }
    
    @Override
    public Result<Boolean> existsByUsername(String username) {
        return Result.success(userDbService.existsByUsername(username));
    }
}